<template>
	<view class="pageContent">
		<view class="install hasMargin">
			<view class="install-site">安装位置</view>
			<view class="installRig noBottom" @click="goSite">
				<view class="installSiteNam">
					{{equipment.gatePostName ? equipment.installationName+'-'+equipment.gatePostName : '请选择点位'}}
				</view>
				<view class="arrow arrowSite" v-if="!globalEquipment"></view>
			</view>
		</view>

		<view class="install">
			<view class="install-site">设备编号</view>
			<view class="installRig">
				<view class="installScan" @click="getScan">{{equipment.equipmentNumber || '请扫描设备码'}}</view>
				<image class="install-icon" :src="localImages +'/yw-scan.png'" @click="getScan" />
			</view>
		</view>
		<view class="install">
			<view class="install-site" @click="setParams">通信类型</view>
			<view class="installRig">
				<view class="installRigTyp" :class="{'check' : connectIndex==index}" v-for="(item,index) in connectList"
					:key="index">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="install">
			<view class="install-site" @click="getCode">门锁类型</view>
			<view class="installRig">
				<view class="installRigTyp" :class="{'check' : lockIndex==index}" v-for="(item,index) in lockList"
					:key="index" @click="lockSel(index)">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="install">
			<view class="install-site">安装方向</view>
			<view class="installRig">
				<view class="installRigTyp" :class="{'check' : directionIndex==index}"
					v-for="(item,index) in directionList" :key="index" @click="directionSel(index)">
					{{item.name}}
				</view>
			</view>
		</view>
		<view class="install">
			<view class="install-site">SIM卡号</view>
			<view class="installRig noBottom">
				<view class="installScan" @click="getScan">{{equipment.sim || ''}}</view>
				<image v-if="0" class="install-icon" :src="localImages +'/yw-scan.png'" @click="getScan" />
			</view>
		</view>

		<view class="install marginTop">
			<view class="install-site">安装拍照</view>
			<view class="installRig">
				<view class="installRigPho" v-for="(item,index) in photoList" :key="index" @click="takePhoto(index)">
					<template v-if="index==0">
						<image v-if="!installPicture1" class="installRigPhoIc" :src="localImages +'/yw-photo.png'" />
						<image v-if="installPicture1" class="installRigPhoIc" :src="installPicture1" />
					</template>
					<template v-if="index==1">
						<image v-if="!installPicture2" class="installRigPhoIc" :src="localImages +'/yw-photo.png'" />
						<image v-if="installPicture2" class="installRigPhoIc" :src="installPicture2" />
					</template>
					<template v-if="index==2">
						<image v-if="!installPicture3" class="installRigPhoIc" :src="localImages +'/yw-photo.png'" />
						<image v-if="installPicture3" class="installRigPhoIc" :src="installPicture3" />
					</template>
					<view>{{item.name}}</view>
				</view>
			</view>
		</view>
		<view class="install">
			<view class="install-site">调试测试</view>
			<view class="installRig">
				<view class="installRigTyp start" :class="{'complete': checkAll}" @click="startTest">
					{{checkAll ? '完成检测' :'开始检测'}}
				</view>
			</view>
		</view>

		<view class="fixedBottom" :class="{'isFullscreen':isFullscreen}">
			<view class="fixedLeft">{{dateStr}}
				<view>{{name || 'name'}} {{phone || 'phone'}}</view>
			</view>
			<view class="fixedMid" @click="checkInstall()">完成</view>
			<view class="fixedRight" @click="freshPage()">继续安装</view>
		</view>

		<scPopup :show="showPop" :showConfirm="false" :showClose="1" @change="closePop">
			<view class="scTitle">设备调试检测</view>
			<view class="scItem">检测联网、心跳正常
				<view class="sc-checkbox scCheck" :class="{'check': checkList[0].checked}" @click="checkTap(0)"></view>
			</view>
			<view class="scItem">检测远程开门正常
				<view class="scRemote" @click="remoteControl">远程开门</view>
				<view class="sc-checkbox scCheck" :class="{'check': checkList[1].checked}" @click="checkTap(1)"></view>
			</view>
			<view class="scItem">检测密码开门（请在设备上输入{{qrCodeInfo.passwordTemp || ''}}）
				<view class="sc-checkbox scCheck" :class="{'check': checkList[2].checked}" @click="checkTap(2)"></view>
			</view>
			<view class="scItem">检测刷卡开门（请在设备上刷卡）
				<view class="sc-checkbox scCheck" :class="{'check': checkList[3].checked}" @click="checkTap(3)"></view>
			</view>
			<view class="scItem">检测人脸开门（请将人脸对准设备摄像头）
				<view class="sc-checkbox scCheck" :class="{'check': checkList[4].checked}" @click="checkTap(4)"></view>
			</view>
		</scPopup>

	</view>
</template>

<script>
	import config from '../../static/config.js'
	import util from '../../static/utils/util.js'
	import scPopup from '../../components/scPopup/scPopup.vue'

	export default {
		components: {
			scPopup
		},
		data() {
			return {
				images: config.images,
				localImages: config.localImages,
				title: '123',
				connectList: [{
						name: '无线',
						type: false
					},
					{
						name: '有线',
						type: true,
					}
				],
				connectIndex: -1,
				lockList: [{
						name: '电控锁',
						type: 1
					},
					{
						name: '磁力锁',
						type: 2,
					}
				],
				lockIndex: -1,
				directionList: [{
						name: '入口',
						type: 1
					},
					{
						name: '出口',
						type: 2,
					}
				],
				directionIndex: -1,
				equipment: {
					gatePostId: "",
					gatePostName: "",
					installationName: ""
				},
				installSite: {
					gatePostId: "",
					gatePostName: "",
					installationName: ""
				},
				photoList: [{
						name: '安装前',
						key: 'installPicture1',
						type: 1
					},
					{
						name: '安装后',
						key: 'installPicture2',
						type: 2,
					}
				],
				installPicture1: '',
				installPicture2: '',
				installPicture3: '',
				showPop: 0,
				checkList: [{
						checked: false,
						name: '检测联网、心跳正常',
						value: '1',
					},
					{
						checked: false,
						name: '检测远程开门正常',
						value: '2',
					},
					{
						checked: false,
						name: '检测联网、心跳正常',
						value: '3',
					},
					{
						checked: false,
						name: '检测联网、心跳正常',
						value: '4',
					},
					{
						checked: false,
						name: '检测联网、心跳正常',
						value: '5',
					}
				],
				checkAll: false,
				dateStr: '',
				phone: '',
				name: '',
				faceInfo: '',
				faceUrl: "",
				qrCodeInfo: {},
				globalEquipment: '',
				isBind: false,
				isFullscreen: false,
			}
		},

		watch: {
			checkList: {
				handler(val, oldVal) {
					var checkAll = val.every((item) => item.checked == true)
					console.log('checkAll', checkAll)
					this.checkAll = checkAll
				},
				deep: true,
			}
		},

		onLoad() {
			var dateStr = util.newDateYearMonDa()
			this.dateStr = dateStr
			this.phone = wx.getStorageSync('phone')
			this.name = wx.getStorageSync('info').name

			//全面屏幕底部高度适配
			var isFullscreen = false
			var systemInfo = wx.getSystemInfoSync()
			var safeArea = systemInfo.safeArea
			console.log('top=', systemInfo.safeArea.top)
			console.log('bottom=', systemInfo.safeArea.bottom)
			console.log('screenHeight=', systemInfo.screenHeight)
			console.log('safeArea=', systemInfo.safeArea)
			console.log('systemInfo=', systemInfo)
			//苹果机型方法1:
			if (systemInfo.screenHeight > systemInfo.safeArea.bottom) {
				if (/ios/i.test(systemInfo.system)) {
					isFullscreen = true
					this.isFullscreen = isFullscreen
				}
			}
			//苹果机型方法2:高度大于812的是全面屏
			if (/ios/i.test(systemInfo.system) && systemInfo.screenHeight >= 812) {
				isFullscreen = true
				this.isFullscreen = isFullscreen
			}
			//安卓机型:以1080X2340=>360X780,height=780.非全面屏模式下:height=780-44=736
			//可以适配分辨率大于2208(736*3)的大部分安卓手机
			if (/android/i.test(systemInfo.system) && systemInfo.screenHeight > 736) {
				isFullscreen = true
				this.isFullscreen = isFullscreen
			}

		},
		onShow() {
			this.updateSite()
			//从我的工单传递过来的参数
			var equipment = getApp().globalData.equipment
			this.globalEquipment = equipment
			if (equipment) {
				console.log('equipment', equipment)
				this.installPicture1 = this.imageUrl(equipment.installPicture1)
				this.installPicture2 = this.imageUrl(equipment.installPicture2)
				// this.installPicture3 = this.imageUrl(equipment.installPicture3)
				this.showParam(equipment)
			}
		},
		onUnload() {
			getApp().globalData.installSite = '' //清空安装位置数据
			getApp().globalData.equipment = '' //清空待安装工单数据
			this.globalEquipment = ''
		},
		methods: {
			lockSel(index) {
				this.lockIndex = index
				this.equipment.gateLockType = this.lockList[index].type
			},
			directionSel(index) {
				this.directionIndex = index
				this.equipment.direction = this.directionList[index].type
			},
			// 更新安装位置
			updateSite() {
				var installSite = getApp().globalData.installSite
				if (installSite) {
					console.log('installSite', installSite)
					this.equipment['gatePostName'] = installSite.gatePostName
					this.equipment['installationName'] = installSite.installationName
					this.equipment['gatePostId'] = installSite.gatePostId
				}
			},
			async checkTap(index) {
				if (index == 4) {
					var face = await this.faceSatus()
					// console.log('face',face)
					if (this.faceInfo.faceSwitch != 3) {
						if (!this.checkList[index].checked) {
							this.onShowModal()
						}
					}
				}
				this.checkList[index].checked = !this.checkList[index].checked
			},

			onShowModal() {
				var self = this;
				wx.showModal({
					title: '温馨提示',
					content: '检测到您没有上传人脸图片。',
					cancelColor: "#999999",
					confirmColor: "#1086FF",
					confirmText: '上传',
					cancelText: '取消',
					success(res) {
						if (res.confirm) {
							self.imagePhoto();
						} else if (res.cancel) {}
					}
				})
			},

			// 我的-安装检测-刷脸上传-图片上传
			imagePhoto() {
				var self = this;
				wx.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					async success(res) {
						const tempFilePaths = res.tempFilePaths
						var src = res.tempFilePaths[0]
						var param = await util.uploadFile(src)
						self.faceUrl = param.filePath
						self.faceSwitch()
					},
					fail(res) {
						console.warn('fail', res)
					},
					complete(res) {
						console.warn('complete', res)
					}
				})
			},

			async faceSwitch() {
				var url = '/UserServer/mini/install/faceSwitch'
				var params = {
					faceSwitch: 1,
					faceUrl: this.faceUrl,
					gatePostId: this.equipment.gatePostId,
					equipmentNumber: this.equipment.equipmentNumber
				}
				// var paramUrl = util.stringifyQs(params)
				// url = "?" + paramUrl
				var method = "PUT"
				var header = false
				var options = {
					url,
					params,
					method,
					header
				}
				var param = await util.requestPro(options)
				console.log('param', param)
				wx.showToast({
					title: "图片上传成功",
					icon: 'none'
				});
			},

			setParams() {
				var equipment = {
					"adEnable": 0,
					"communicationType": true,
					"creatTime": null,
					"createTime": 1636019780000,
					"direction": 2,
					"entryEnable": 0,
					"equipmentId": 13,
					"equipmentIp": "",
					"equipmentKey": "",
					"equipmentModifyTime": null,
					"equipmentName": "ceshi",
					"equipmentNumber": "21PD0000003A",
					"equipmentStatus": 1,
					"equipmentTypeId": 0,
					"faceSync": 0,
					"gateLockModifyTime": null,
					"gateLockStatus": 0,
					"gateLockType": 1,
					"gatePostId": 66,
					"gatePostName": "车库门xxx",
					"gatePostType": 2,
					"installPicture1": "/picture/owner/2021-11-04/1636019500974.jpg",
					"installPicture2": "/picture/owner/2021-11-04/1636019503358.jpg",
					"installPicture3": "/picture/owner/2021-11-04/1636019506181.jpg",
					"installationName": "黄胜小区1-2栋-2单元",
					"installerId": 0,
					"mac": "",
					"modifyTime": 1636082979000,
					"projectId": 0,
					"regionOrUnitId": 0,
					"sim": "",
					"status": 1,
					"timingLockEnable": 0
				}

				this.installPicture1 = this.imageUrl(equipment.installPicture1)
				this.installPicture2 = this.imageUrl(equipment.installPicture2)
				// this.installPicture3 = this.imageUrl(equipment.installPicture3)
				this.showParam(equipment)
			},

			imageUrl(url) {
				return config.IMAGE_APIHOST + url //拼接前缀地址
			},

			startTest() {
				// this.installTask()
				if (!this.equipment.gatePostId) {
					wx.showToast({
						title: "请选择点位",
						icon: 'none'
					});
					return
				}
				if (!this.equipment.equipmentNumber) {
					wx.showToast({
						title: "请扫描设备码",
						icon: 'none'
					});
					return
				}
				if (!this.equipment.installPicture1 || !this.equipment.installPicture2) {
					wx.showToast({
						title: "请上传安装图片",
						icon: 'none'
					});
					return
				}
				this.installTask()
				// this.openPop()
			},

			openPop() {
				this.showPop = true
			},

			async installTask() {
				var url = '/UserServer/mini/install/installTask'
				var params = this.equipment
				// var params = {
				// 	"gatePostId": 65,
				// 	"communicationType": true,
				// 	"gateLockType": 1,
				// 	"direction": 1,
				// 	"equipmentNumber": "21PD0000003A",
				// 	"mac": "",
				// 	"equipmentName": "周凡测试",
				// 	"installPicture1": "string",
				// 	"installPicture2": "string",
				// 	"installPicture3": "string"
				// }
				var method = 'POST'
				var showToast = true
				var options = {
					url,
					method,
					params,
					showToast
				}
				//如果绑定完成，或者从我的工单里面过来的数据不需要调用install安装接口
				if (this.isBind || this.globalEquipment) {
					this.verifyEquipmentStatus()
					this.qrCode()
					await this.faceSatus()
				} else {
					try {
						var param = await util.requestPro(options)
						this.isBind = true
					} catch (e) {
						console.log('installTask', e)
					} finally {

					}
				}

			},
			closePop(popup) {
				var type = popup.type
				if (type) {} else {}
				this.showPop = false
			},
			async verifyEquipmentStatus() {
				var url = '/UserServer/mini/install/verifyEquipmentStatus'
				var params = {
					equipmentNumber: this.equipment.equipmentNumber || '123'
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				// console.log('param', param)
				this.showPop = true
				this.checkList[0].checked = true
			},
			async qrCode() {
				var url = '/UserServer/mini/install/qrCode'
				var params = {
					gatePostId: this.equipment.gatePostId || '123'
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				console.log('param', param)
				this.qrCodeInfo = param
			},
			async faceSatus() {
				var url = '/UserServer/mini/install/faceSatus'
				var params = {
					equipmentId: this.equipment.equipmentId || '123',
					gatePostId: this.equipment.gatePostId || '123'
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				this.faceInfo = param
				return new Promise((resolve) => resolve(1))
			},

			async checkInstall() {
				var length = this.checkList.filter(item => item.checked).length
				if (length < 2) {
					wx.showToast({
						title: '请先开始检测',
						icon: 'none',
						duration: 800,
					})
					return
				}
				var url = '/UserServer/mini/install/checkInstall'
				var params = {
					equipmentNumber: this.equipment.equipmentNumber,
					gatePostId: this.equipment.gatePostId
				}
				var method = "PUT"
				var header = false
				var options = {
					url,
					params,
					method,
					header
				}
				var param = await util.requestPro(options)
				console.log('param', param)
				wx.showToast({
					title: '安装成功',
					icon: 'none',
					duration: 1200,
				})
				setTimeout(() => {
					this.returnMain()
				}, 800)
			},

			returnMain() {
				wx.switchTab({
					url: '/pages/index/index'
				})
			},
			freshPage() {
				wx.reLaunch({
					url: '/pages/index/install'
				})
			},
			goSite() {
				if (this.globalEquipment) {
					return
				}
				wx.navigateTo({
					url: '/pages/index/selectSite'
				})
			},
			getCode() {
				var param = {
					"adEnable": 0,
					"communicationType": true,
					"createTime": 1635219107000,
					"direction": 1,
					"entryEnable": 0,
					"equipmentId": 92,
					"equipmentIp": "",
					"equipmentKey": "",
					"equipmentModifyTime": null,
					"equipmentName": "鲁班8号",
					"equipmentNumber": "21PD0000002A",
					"equipmentStatus": 2,
					"equipmentTypeId": 1,
					"gateLockModifyTime": null,
					"gateLockStatus": 0,
					"gateLockType": 1,
					"gatePostId": 65,
					"mac": "",
					"networkSignal": false,
					"sim": "123",
					"timingLockEnable": 0
				}
				this.showParam(param)
			},
			getScan() {
				var self = this
				wx.scanCode({
					success(res) {
						var equipmentNumber = res.result
						self.installEquipment(equipmentNumber)
					},
					fail(res) {
						console.log('scanCode=fail', res)
					}
				})
			},
			async installEquipment(equipmentNumber = '') {
				var url = '/UserServer/mini/install/installEquipment'
				var params = {
					equipmentNumber: equipmentNumber
				}
				var options = {
					url,
					params
				}
				var param = await util.requestPro(options)
				console.log('this.installEquipment=', param)
				param = Object.assign(this.equipment, param)
				this.updateSite()
				this.showParam(param)
			},
			showParam(equipment) {
				this.equipment = equipment
				this.connectList.forEach((item, index) => {
					if (item.type == equipment.communicationType) {
						this.connectIndex = index
					}
				})
				this.lockList.forEach((item, index) => {
					if (item.type == equipment.gateLockType) {
						this.lockIndex = index
					}
				})
				this.directionList.forEach((item, index) => {
					if (item.type == equipment.direction) {
						this.directionIndex = index
					}
				})
			},

			//图片上传
			takePhoto(index) {
				var self = this;
				var key = this.photoList[index].key
				wx.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera'],
					success(res) {
						const tempFilePaths = res.tempFilePaths
						var src = res.tempFilePaths[0];
						util.uploadFile(src).then((res) => {
							var param = res;
							var urlPath = param.url + param.filePath;
							switch (key) {
								case 'installPicture1':
									self.installPicture1 = urlPath;
									self.equipment[key] = param.filePath;
									break;
								case 'installPicture2':
									self.installPicture2 = urlPath;
									self.equipment[key] = param.filePath;
									break;
								case 'installPicture3':
									self.installPicture3 = urlPath;
									self.equipment[key] = param.filePath;
									break;
								default:
									break;
							}
						})

					}
				})
			},

			async remoteControl() {
				wx.showLoading({
					title: '开门中...',
					mask: true,
					duration: 1200
				})
				var url = '/UserServer/mini/gate/remoteControl'
				var params = {
					equipmentId: this.equipment.equipmentId || '123'
				}
				var paramsUrl = util.stringifyQs(params)
				console.log('paramsUrl', params, paramsUrl.toString())
				url = url + '?' + paramsUrl
				var method = 'POST'
				var options = {
					url,
					method
				}
				var param = await util.requestPro(options)
			},

		},

	}
</script>

<style>
	.pageContent {}

	.install {
		background: #FFFFFF;
		display: flex;
		justify-content: space-between;
		margin: 0rpx 0rpx 0rpx 0rpx;
		padding: 0rpx 30rpx 0rpx 30rpx;
		height: 90rpx;
		line-height: 90rpx;
		font-size: 30rpx;
	}

	.install.hasMargin {
		margin: 14rpx 0rpx 14rpx 0rpx;
	}

	.install.hasPad {
		padding-bottom: 30rpx;
	}

	.install.marginTop {
		margin: 14rpx 0rpx 0rpx 0rpx;
		height: 110rpx;
		line-height: 110rpx;
	}

	.install-site {
		width: 160rpx;
		font-weight: 600;
		color: #333333;
	}

	.installRig {
		flex: 1;
		color: #2035E0;
		text-align: right;
		border-bottom: 1rpx solid #E7E7E7;
		/* border: 1rpx solid #E7E7E7; */
	}

	.installRig.noBottom {
		border-bottom: 1rpx solid transparent;
	}

	.installSiteNam {
		display: inline-block;
		width: 488rpx;
		vertical-align: middle;
		line-height: 40rpx;
		/* border: 1rpx solid red; */
	}

	.install-icon {
		display: inline-block;
		width: 40rpx;
		height: 40rpx;
		margin-left: 20rpx;

		vertical-align: middle;

	}

	.installRigTyp {
		display: inline-block;
		border: 1rpx solid;
		border-radius: 10rpx;
		width: 120rpx;
		height: 46rpx;
		line-height: 44rpx;
		vertical-align: middle;
		text-align: center;
		white-space: nowrap;
		margin: 0rpx 0rpx 0rpx 16rpx;
	}

	.installRigTyp.check {
		background: #2035E0;
		color: #F9F9F9;
	}

	.installRigTyp.start {
		width: 150rpx;
	}

	.installRigTyp.complete {
		color: #fff;
		background-color: #4CD964;
	}

	.installRigPho {
		display: inline-block;
		border-radius: 10rpx;
		width: 90rpx;
		height: 46rpx;
		line-height: 44rpx;
		/* vertical-align: middle; */
		text-align: right;
		font-size: 22rpx;
		color: #333333;
		margin: 10rpx 0rpx 0rpx 40rpx;
		/* border: 1rpx solid; */
	}

	.installRigPhoIc {
		display: inline-block;
		width: 68rpx;
		height: 48rpx;
		margin-left: 0rpx;
		vertical-align: middle;

	}

	.arrow.arrowSite {
		display: inline-block;
		width: 24rpx;
		height: 24rpx;
		margin-left: 14rpx;
		line-height: 90rpx;
		vertical-align: middle;

	}

	.installScan {
		display: inline-block;
		color: #999999;
	}

	.fixedBottom {
		position: fixed;
		display: flex;
		bottom: 0;
		left: 0;
		height: 90rpx;
		line-height: 90rpx;
		width: 100%;
		text-align: center;
		font-weight: 600;
		z-index: 999;
		border: 1rpx solid #2035E0;
	}

	.fixedLeft {
		width: 320rpx;
		color: #fff;
		font-size: 26rpx;
		line-height: 30rpx;
		background-color: #FF6E5D;
		padding: 10rpx 0rpx 0rpx 0rpx;
	}

	.fixedMid {
		width: 180rpx;
		color: #fff;
		background: #2035E0;
	}

	.fixedRight {
		width: 250rpx;
		color: #2035E0;
		background: #fff;
	}

	/* 弹窗 */
	.scTitle {
		text-align: center;
		font-size: 30rpx;
		font-weight: 600;
		padding-bottom: 30rpx;
	}

	.scItem {
		height: 66rpx;
		line-height: 66rpx;
		/* border: 1rpx solid #E7E7E7; */
	}

	.scRemote {
		display: inline-block;
		margin: 0rpx 0rpx 0rpx 22rpx;
		height: 48rpx;
		line-height: 48rpx;
		font-size: 30rpx;
		margin: 10rpx 0rpx 0rpx 20rpx;
		padding: 0rpx 10rpx 0rpx 10rpx;
		background: #007AFF;
		border-radius: 10rpx;
		color: #FFFFFF;
	}

	.scCheck {
		float: right;
		color: #007AFF;
		height: 66rpx;
		line-height: 66rpx;
	}
</style>
